package com.malex.mxtracker;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.malex.mxtracker.bean.DataPackage;
import com.malex.mxtracker.storage.DatabaseManager;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Manusovich Alexander
 */
public class MainActivity extends Activity {
    private NotificationManager nm;
    private DatabaseManager db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        db = new DatabaseManager(getApplicationContext());
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
        final PendingIntent contentIntent = PendingIntent.getActivity(
                getApplicationContext(), 0, notificationIntent, 0);
        final Notification notification = new Notification(-1, "", System.currentTimeMillis());

        MxTrackerUpdater.setUpdateListener(new ServiceUpdateUIListener() {
            public void updateUI(final boolean value) {
                runOnUiThread(
                        new Runnable() {
                            public void run() {
                                String s = "internet: " + value + " t: "
                                        + new SimpleDateFormat("HH:mm:ss").format(new Date());

                                TextView mStatusText = (TextView) findViewById(R.id.status);
                                mStatusText.setText(s);

                                notification.setLatestEventInfo(getApplicationContext(),
                                        "status", s, contentIntent);
                                nm.notify(1, notification);
                            }
                        });
            }
        });
        Intent svc = new Intent(this, MxTrackerUpdater.class);
        startService(svc);

        setContentView(R.layout.main);

        Button button = (Button) findViewById(R.id.incomingButton);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(final View view) {
                addIncoming();
            }
        });

        Button exButton = (Button) findViewById(R.id.expenseButton);
        exButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(final View view) {
                String values = "";
                Cursor c = db.fetchAllNotes();
                int valueCI = c.getColumnIndex("value");
                while (c.moveToNext()) {
                    values += c.getDouble(valueCI) + ", ";
                }
                EditText mBodyText = (EditText) findViewById(R.id.body);
//                mBodyText.setText(values);

                /**
                 * Запрашиваем данные с сервера
                 */
                URL url;
                try {
                    url = new URL("http://mxtracker.appspot.com/data?p=true&b=true");
                    URLConnection conn = url.openConnection();
                    BufferedReader rd = new BufferedReader(new
                            InputStreamReader(conn.getInputStream()));
                    String line;
                    if ((line = rd.readLine()) != null) {
                        DataPackage dp = null;
                        try {
                            ObjectMapper om = new ObjectMapper();
                            dp = om.readValue(line, DataPackage.class);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        System.out.println("data = " + dp);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void addIncoming() {
        db.addIncoming();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent svc = new Intent(this, MxTrackerUpdater.class);
        stopService(svc);
    }
}
